#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <iostream>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include<functional>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"
using namespace std;

const static int defaultfd = -1;
const static int backlog = 16;


enum
{
    SOCK_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR,
};

class TcpServer;
class ThreadData
{
public:
    ThreadData(int fd, InetAddr addr, TcpServer *s) : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

using task_t = std::function<void()>;

class TcpServer
{
public:
    TcpServer(int port) : _port(port), _listensock(defaultfd), _isrunning(false)
    {
    }
    void InitServer()
    {
        // 1. 创建流式套接字
        _listensock = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            LOG(FATAL, "socket error");
            exit(SOCK_ERROR);
        }
        LOG(DEBUG, "socket create success, sockfd is : %d\n", _listensock);

        // 2. bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = ::bind(_listensock, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success, sockfd is : %d\n", _listensock);

        // 3. tcp是面向连接的，所以通信之前，必须先建立连接。服务器是被连接的
        //    tcpserver 启动，未来首先要一直等待客户的连接到来
        n = ::listen(_listensock, backlog);
        if (n < 0)
        {
            LOG(FATAL, "listen error");
            exit(LISTEN_ERROR);
        }
        LOG(DEBUG, "listen success, sockfd is : %d\n", _listensock);
    }
    void Service(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link, info %s:%d\n", client.Ip().c_str(), client.Port());

        string clientaddr = "[" + client.Ip() + ":" + to_string(client.Port()) + "]# ";
        while (true)
        {
            // ssize_t read(int fd, void *buf, size_t count);
            char inbuffer[1024];
            ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer) - 1);
            if (n > 0)
            {
                inbuffer[n] = 0;
                cout << clientaddr << inbuffer << endl;

                string echo_string = "[server echo]# ";
                echo_string += inbuffer;

                // ssize_t write(int fd, const void *buf, size_t count);
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                // 客户端退出 && 关闭链接
                LOG(INFO, "%s quit\n", clientaddr.c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n");
                break;
            }
        }
        close(sockfd); // 不关闭就会产生文件描述符的泄漏问题
    }
    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->Service(td->sockfd, td->clientaddr);
        delete td;
        return nullptr;
    }
    void Loop()
    {
        // 4.不能直接收取数据，要先获取连接
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
            // 返回值是一个文件描述符，用来进行通信的
            int sockfd = accept(_listensock, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error,%s,%s\n", strerror(errno), errno);
                continue;
            }
            LOG(INFO, "accept success!\n");
            // 版本0
            // InetAddr addr(peer);
            // Service(sockfd, addr);

            // 版本1 多进程
            //  pid_t id=fork();
            //  if(id==0)
            //  {
            //      //子进程关心sockfd，不关心listensock
            //      close(_listensock);//建议
            //      if(fork()>0)    exit(0);
            //      Service(sockfd, InetAddr(peer));//孙子进程--孤儿进程
            //      exit(0);
            //  }
            //  //父进程关心listensock，不关心sockfd
            //  close(sockfd);

            // 版本3 多线程
            // pthread_t t;
            // ThreadData *td = new ThreadData(sockfd, InetAddr(peer), this);
            // pthread_create(&t, nullptr, HandlerSock, td); // 将线程分离

            // vesion 3: 采用线程池
            task_t t = std::bind(&TcpServer::Service, this, sockfd, InetAddr(peer));
            ThreadPool<task_t>::GetInstance()->Enqueue(t);
        }
        _isrunning = false;
    }
    ~TcpServer()
    {
        if (_listensock > defaultfd)
            close(_listensock);
    }

private:
    uint16_t _port;
    int _listensock; // 监听套接字
    bool _isrunning;
};